<?php
/**
 * 资源分类标签库基础业务
 * @author yxt 2013年1月15日15:05:05
 * 缓存的key为label
 */
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nl_common.func.php';
//include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'label'.DIRECTORY_SEPARATOR.'asset_item_bo.class.php';
class nl_video_label{
	//缓存时间
	static private $cache_time=3600;
	//允许插入的字段
	static $add_fields=array("name"=>"","type"=>"","state"=>"","source"=>"");
	//允许修改的字段
	static $modify_fields=array();
	//排序规则
	static $order=array(
			NL_ORDER_TIME_ASC=>" order by nns_create_time asc",
			NL_ORDER_TIME_DESC=>" order by nns_create_time desc",
			NL_ORDER_CLICK_ASC=>" order by nns_times asc",
			NL_ORDER_CLICK_DESC=>" order by nns_times desc",
	);
	/**
	 * 插入标签,前2个是必传递参数
	 * @param $dc
	 * @param $name:标签名称
	 * @param array $params:一维数组
	 * array("type"=>标签类型,"times"=>使用次数,"state"=>是否启用,"source"=>标签来源)
	 * @param bool $if_hand 是否为手动添加，默认为否
	 * @return string 标签id,失败返回false，如果为手动添加，标签已经存在返回-1
	 */
	static public function add_video_label($dc,$name,$params=array(),$if_hand=false){
		//先判断标签是否存在
		$sql="select nns_id from nns_video_label where nns_name='{$name}' and nns_type='{$params['type']}' and nns_source ='{$params['source']}'";

		$if_exist=nl_query_by_db($sql,$dc->db());
		if(!is_bool($if_exist)){
			if($if_hand==true){
				return -1;
			}
			//如果有这个标签，则将标签包含的影片数据+1
			$sql="update nns_video_label set nns_count=nns_count+1 where nns_id='{$if_exist[0]['nns_id']}'";
			nl_execute_by_db($sql, $dc->db());
			return $if_exist[0]['nns_id'];
		}
		if($if_exist===false){
			return false;
		}
		//id使用当前数据库中最大的标签id+1
		$sql="select max(nns_id+0) as max from nns_video_label where nns_type='{$params['type']}'";
		$r=nl_query_by_db($sql, $dc->db());
//		echo '$r:'.var_export($r,true)."\n";
		if($r[0]["max"]===NULL){
			$id=$params['type']."00000001";
		}else{
			$id=$r[0]["max"]+1;
			//$id=str_pad($id, 8, "0", STR_PAD_LEFT);
		}
//		echo 'id:'.$id."\n";
		$params["id"]=$id;
		$params["name"]=$name;
		$params["create_time"]=date("Y-m-d H:i:s",time());
		if($if_hand==true){
			$params["count"]=1;
		}
// 		修复未初始化变量错误提示--wuha 2013-3-27
		$fields	= $values = '';
		foreach ($params as $key=>$val){
			$fields.="nns_{$key},";
			$values.="'{$val}',";
		}
		$fields=trim($fields,',');
		$values=trim($values,',');
		//组织sql
		$sql="insert into nns_video_label({$fields}) values({$values})";
		$ret=nl_execute_by_db($sql, $dc->db());
		//如果成功删除缓存key
		if($ret){
			self::del_cache($dc);
			return (string)$id;
		}
//		var_dump($sql);
		return $ret;
	}
	static public function edit_video_label($dc,$video_label){
		if(empty($video_label)){
			return false;
		}
		$sql = "update nns_video_label set nns_type='".$video_label['nns_type']."' where nns_id='".$video_label['label_id']."'";
		$ret=nl_execute_by_db($sql, $dc->db());
		//如果添加成功则删除缓存
		if($ret){
			self::del_cache($dc);
		}
		return $ret;
	}
	/**
	 * @param $dc
	 * @param string $id:标签id
	 * @param string $state
	 * @return bool
	 */
	static public function update_video_label_state_by_id($dc,$id,$state){
		if(empty($id)){
			return false;
		}
		$sql="update nns_video_label set nns_state='{$state}' where nns_id='{$id}'";
		$ret=nl_execute_by_db($sql, $dc->db());
		//如果添加成功则删除缓存
		if($ret){
			self::del_cache($dc);
		}
		return $ret;
	}
	/**
	 * @param $dc,
	 * @param array $params
	 * Array(“type”=>标签类型,“source”=>标签来源,“state”=>标签状态,“name”=>标签内容 )
	 * @param bool $if_like:是否使用like查询，默认为false[不使用]
	 * @param string $log:字段之间的逻辑连接关系，默认AND
	 * @return int $count
	 */
	static public function count_video_label ($dc,$params=array(),$if_like=false,$log='AND'){
		 if(!is_array($params)){
			 $params=array();
		 }
		if(isset($params['assest_id']) && isset($params['category_id'])){
			$assest_id = $params['assest_id'];
			unset($params['assest_id']);
			$category_id = $params['category_id'];
			unset($params['category_id']);
			$sql = '';
			foreach ($params as $key=>$val){
				if($key=='name'){
					if($if_like){
						$sql.="nns_{$key} like '%{$val}%' and ";
					}else{
						$sql.="nns_{$key}='{$val}' and ";
					}
				}else{
					$sql.="nns_{$key}='{$val}' and ";
				}
			}
			$sql="select count(1) as num from nns_video_label where nns_id not in(select nns_label_id from nns_assest_lable_bind where nns_assest_id ='$assest_id' and nns_category_id='$category_id') and {$sql}";
		  
			$sql = rtrim($sql,' and ');
		}else{
			$sql = ' where ';

			foreach ($params as $key=>$val){
				if($key=='name'){
					if($if_like){
						$sql.="nns_{$key} like '%{$val}%' and ";
					}else{
						$sql.="nns_{$key}='{$val}' and ";
					}
				}else{
					$sql.="nns_{$key}='{$val}' and ";
				}
			}

				$sql = "select count(1)as num from nns_video_label ".rtrim($sql,' and ');

		}
									  
		$res = nl_query_by_db($sql, $dc->db());

//        if($res!==false){//如果获取成功，判断是否打开缓存，如果打开则缓存起来
//            if($dc->is_cache_enabled()){
//                $cache=$dc->cache();
//                //获取key，失败则创建新的key
//                $key=$cache->get("label_count");
//                if(empty($key)){
//                    $key=time();
//                    $cache->set("label_count",$key,self::$cache_time);
//                }
//                $key_sql="label_count|#".md5($sql);
//                $cache->set("label_count|#".$key."|#".$key_sql,$res,self::$cache_time);
//            }
//        }
		return $res['0']['num'] == NULL ?0:$res['0']['num'];
	}
	/**
	 * 统计绑定包数据
	 */
	static public function count_bind ($dc,$params=array(),$if_like=false,$log='AND'){
		if(!is_array($params)){
			$params=array();
		}
		if(isset($params['assest_id']) && isset($params['category_id'])){
			$assest_id = $params['assest_id'];
			unset($params['assest_id']);
			$category_id = $params['category_id'];
			unset($params['category_id']);
			$sql = '';
			foreach ($params as $key=>$val){
				if($key=='name'){
					if($if_like){
						$sql.="nns_{$key} like '%{$val}%' and ";
					}else{
						$sql.="nns_{$key}='{$val}' and ";
					}
				}else{
					$sql.="nns_{$key}='{$val}' and ";
				}
			}
			$sql="select count(1) as num from nns_video_label where nns_id not in(select nns_label_id from nns_assest_lable_bind where nns_assest_id ='$assest_id' and nns_category_id='$category_id') and {$sql}";
	
			$sql = rtrim($sql,' and ');
		}else{
			$sql = '';
			$sql_ex = '';
			foreach ($params as $key=>$val){
				if($key=='name'){
					if($if_like){
						$sql_ex.="nns_{$key} like '%{$val}%' and ";
					}else{
						$sql_ex.="nns_{$key}='{$val}' and ";
					}
				}else{
					$sql_ex.="nns_{$key}='{$val}' and ";
				}
			}
			//-->start xingcheng.hu 去掉where1=1
			if(!empty($sql_ex))
			{
				$sql .= 'where ';
				$sql .= $sql_ex;
			}
			//<--end
			$sql = "select count(1) as num from nns_video_label ".rtrim($sql,' and ');
	
		}
			
		$res = nl_query_by_db($sql, $dc->db());
	
		//        if($res!==false){//如果获取成功，判断是否打开缓存，如果打开则缓存起来
		//            if($dc->is_cache_enabled()){
		//                $cache=$dc->cache();
		//                //获取key，失败则创建新的key
		//                $key=$cache->get("label_count");
		//                if(empty($key)){
		//                    $key=time();
		//                    $cache->set("label_count",$key,self::$cache_time);
		//                }
		//                $key_sql="label_count|#".md5($sql);
		//                $cache->set("label_count|#".$key."|#".$key_sql,$res,self::$cache_time);
		//            }
		//        }
		return $res['0']['num'] == NULL ?0:$res['0']['num'];
	}
	
	
	/**
	 * 将标签查询量+1
	 * @param $dc
	 * @param string $id
	 * @return bool
	 */
	static public function count_video_label_times_by_id($dc,$id){
		if(empty($id)){
			return  false;
		}
		$sql="update nns_video_label set nns_times=nns_times+1 where nns_id='{$id}'";
		return nl_execute_by_db($sql, $dc->db());
	}
	/**
	 * 获取标签列表
	 * @param $dc
	 * @param array $params：筛选条件
	 * Array(
				“type”=>标签类型
				“state”=>标签状态
				“name”=>标签内容 =查询
			)
	 * @param int $since 起始查询记录位置 0表示第一页
	 * @param int $num 查询记录条数
	 * @param bool $if_like:名字字段是否使用like查询，默认不false适用
	 * @param string $order
				NL_ORDER_TIME_ASC 按创建时间升序排列
				NL_ORDER_TIME_ DESC 按创建时间降序排列
				NL_ORDER_CLICK_ASC按点击数升序排列
				NL_ORDER_CLICK_DESC按点击数降序排列,默认
	 * @param string $policy：查询策略
	 * @param array $re:返回二维数组，如果为空则返回空数组
	 * @param bool :查询失败返回false
	 */
	static public function get_video_label_list ($dc,$params,$since,$num,$if_like=false,$order=NL_ORDER_CLICK_DESC,$policy=NL_DC_AUTO){
		if($dc->is_cache_enabled()){
			switch($policy){
				case NL_DC_AUTO:  $result=self::get_video_label_list_cache($dc,$params,$since,$num,$if_like,$order,$policy);break;
				case NL_DC_DB:    $result=self::get_video_label_list_db($dc,$params,$since,$num,$if_like,$order,$policy);break;
				case NL_DC_CACHE: $result=self::get_video_label_list_cache($dc,$params,$since,$num,$if_like,$order,$policy);break;
			}
		}else{
					
			$result=self::get_video_label_list_db($dc,$params,$since,$num,$if_like,$order);
					   
		}
		return $result;
	}
	static private function get_video_label_list_cache($dc,$params,$since,$num,$if_like=false,$order,$policy){
		$cache=$dc->cache();
		//先获取key
		$key=$cache->get("label");
		//如果获取失败则判断是否需要从数据库读取，如果不是则返回空数组
		if($key===false){
			if($policy==NL_DC_AUTO){
				return self::get_video_label_list_db($dc, $params, $since, $num,$if_like, $order);
			}else{
				return true;
			}
		}
		//获取成功则需要获取查询条件，再获取缓存结果
		$key_sql=self::get_sql($params,$since,$num,$order,$if_like);
		$key_sql="label|#".md5($key_sql);
		$get_cache=$cache->get("label|#".$key."|#".$key_sql);
		//如果获取失败则判断是否需要从数据库读取，如果不是则返回空数组
		if($get_cache===false){
			if($policy==NL_DC_AUTO){
				return self::get_video_label_list_db($dc, $params, $since, $num,$if_like, $order);
			}else{
				return true;
			}
		}
		return $get_cache;
	}
	static private function get_video_label_list_db($dc,$params,$since,$num,$if_like=false,$order){
		if(isset($params['assest_id']) && isset($params['category_id'])){
			$assest_id = $params['assest_id'];
			unset($params['assest_id']);
			$category_id = $params['category_id'];
			unset($params['category_id']);
			$sql = '';
			foreach ($params as $key=>$val){
				if($key=='name'){
					if($if_like){
						$sql.="nns_{$key} like '%{$val}%' and ";
					}else{
						$sql.="nns_{$key}='{$val}' and ";
					}
				}else{
					$sql.="nns_{$key}='{$val}' and ";
				}
			}
			
			//$sql="select * from nns_assest_lable_bind as alb join nns_video_label as vl on alb.nns_label_id = vl.nns_id  where alb.nns_assest_id='$assest_id' and alb.nns_category_id='$category_id' and {$sql} 1=1";
			$sql="select * from nns_video_label where nns_id not in(select nns_label_id from nns_assest_lable_bind where nns_assest_id ='$assest_id' and nns_category_id='$category_id') and {$sql}";
			
						$sql = rtrim($sql,' and ');
						
			if(empty($since)&&$since!=="0"&&$since!==0){
				$limit=" ";
			}else{
				if(empty($num)){
					$limit=" limit {$since} ";
				}else{
					$limit=" limit {$since},{$num} ";
				}
			}
			if(!empty($order)){
				$order= self::$order[$order];
			}
			$sql.= $order.$limit;
//			echo $sql;exit;
		}else{
			$where_sql=self::get_sql($params,$since,$num,$order,$if_like);
			$sql="select * from nns_video_label {$where_sql} ";
		}
		
		$res=nl_query_by_db($sql, $dc->db());

		if($res!==false){//如果获取成功，判断是否打开缓存，如果打开则缓存起来
			if($dc->is_cache_enabled()){
				$cache=$dc->cache();
				//获取key，失败则创建新的key
				$key=$cache->get("label");
				if(empty($key)){
					$key=time();
					$cache->set("label",$key,self::$cache_time);
				}
				$key_sql="label|#".md5($where_sql);
				$cache->set("label|#".$key."|#".$key_sql,$res,self::$cache_time);
			}
		}
		return $res;
	}
	 
	
	/**
	 * @param $dc
	 * @param string $name
	 * @param string $policy
	 */
//	static public function get_video_label_list_by_name($dc,$name,$policy=NL_DC_AUTO){
//		if($dc->is_cache_enabled()){
//			switch($policy){
//				case NL_DC_AUTO: $result=self::get_video_label_list_by_name_cache($dc,$name);break;
//				case NL_DC_DB: $result=self::get_video_label_list_by_name_db($dc,$name);break;
//				case NL_DC_CACHE: $result=self::get_video_label_list_by_name_cache($dc,$name);break;
//			}
//		}else{
//			$result=self::get_video_label_list_by_name_db($dc,$name);break;
//		}
//		return $result;
//	}
//	static private function get_video_label_list_by_name_db($dc,$name){
//		$where_sql=self::get_sql(array("name"=>$name),null,null,null);
//		$sql="select * from nns_video_label {$where_sql} ";
//		$res=nl_query_by_db($sql, $dc->db());
//		if($res===true){
//			$res=array();
//		}else if($res!==false){//如果获取成功，判断是否打开缓存，如果打开则缓存起来
//			if($dc->is_cache_enabled()){
//				$cache=$dc->cache();
//				//获取key，失败则创建新的key
//				$key=$cache->get("label");
//				if(empty($key)){
//					$key=time();
//					$cache->set("label",$key,self::$cache_time);
//				}
//				$key_sql="label|#".md5($where_sql);
//				$cache->set("label|#".$key."|#".$key_sql,$res,self::$cache_time);
//			}
//		}
//		return $res;
//	}
//	static private function get_video_label_list_by_name_cache($dc,$name){
//		$where_sql=self::get_sql(array("name"=>$name),null,null,null);
//		$sql="select * from nns_video_label {$where_sql} ";
//		$res=nl_query_by_db($sql, $dc->db());
//		if($res===true){
//			$res=array();
//		}else if($res!==false){//如果获取成功，判断是否打开缓存，如果打开则缓存起来
//			if($dc->is_cache_enabled()){
//				$cache=$dc->cache();
//				//获取key，失败则创建新的key
//				$key=$cache->get("label");
//				if(empty($key)){
//					$key=time();
//					$cache->set("label",$key,self::$cache_time);
//				}
//				$key_sql="label|#".md5($where_sql);
//				$cache->set("label|#".$key."|#".$key_sql,$res,self::$cache_time);
//			}
//		}
//		return $res;
//	}
	/**
	 * @param $dc
	 * @param $type标签类型
	 * @param $since起始页
	 * @param $num每页条数
	 * @param $order排序规则
	 * @param $policy缓存策略
	 */
	static public function epg_get_video_label_by_type ($dc,$type,$since,$num,$order,$policy=NL_DC_AUTO){
		if($dc->is_cache_enabled()){
			switch($policy){
				case NL_DC_AUTO: $result=self::epg_get_video_label_by_type_cache($dc,$type,$since,$num,$order,$policy);break;
				case NL_DC_DB: $result=self::epg_get_video_label_by_type_db($dc,$type,$since,$num,$order);break;
				case NL_DC_CACHE: $result=self::epg_get_video_label_by_type_cache($dc,$type,$since,$num,$order,$policy);break;
			}
		}else{
			$result=self::epg_get_video_label_by_type_db($dc,$type,$since,$num,$order);
		}
		return $result;
	}
	static private function epg_get_video_label_by_type_db ($dc,$type,$since,$num,$order){
		$where_sql=self::get_sql(array("type"=>$type),$since,$num,$order);
		$sql="select * from nns_video_label {$where_sql} ";
		$res=nl_query_by_db($sql, $dc->db());
		if($res!==false){//如果获取成功，判断是否打开缓存，如果打开则缓存起来
			if($dc->is_cache_enabled()){
				$cache=$dc->cache();
				//获取key，失败则创建新的key
				$key=$cache->get("label");
				if(empty($key)){
					$key=time();
					$cache->set("label",$key,self::$cache_time);
				}
				$key_sql="label|#".md5($where_sql);
				$cache->set("label|#".$key."|#".$key_sql,$res,self::$cache_time);
			}
		}
		return $res;
	}
	static private function epg_get_video_label_by_type_cache ($dc,$type,$since,$num,$order,$policy=NL_DC_AUTO){
		$where_sql=self::get_sql(array("type"=>$type),$since,$num,$order);
		//获取缓存key
		$key=$dc->cache()->get("label");
		if($key===false){//如果获取失败，判断是否需要从数据库获取
			if($policy==NL_DC_AUTO){
				return self::epg_get_video_label_by_type_db($dc,$type,$since,$num,$order);
			}else{
				return true;
			}
		}
		$key_sql="label|#".md5($where_sql);
		//获取缓存数据
		$cache_data=$dc->cache()->get("label|#".$key."|#".$key_sql);
		if(!empty($cache_data)){
			return $cache_data;
		}
		if($cache_data===false){//如果获取失败，判断是否需要从数据库获取
			if($policy==NL_DC_AUTO){
				return self::epg_get_video_label_by_type_db($dc,$type,$since,$num,$order);
			}else{
				return true;
			}
		}
		return $cache_data;
	}

	/**
	 * 返回提供查询使用的where条件字符串
	 * @param array $params:查询的一维字段=>值数组,不带前缀nns_
	 * @param int $since起始页
	 * @param int $num每页大小
	 * @param string $order :排序规则
	 * @param string $if_like:是否使用like查询，
	 * @param bool $log:字段之间的逻辑连接关系，默认为AND
	 * @retur string $sql:返回是的包含了"where"的条件语句
	 */
	static private function get_sql($params=array(),$since=null,$num=null,$order=null,$if_like=false,$log="AND"){
		if(empty($params)){
			$sql="";
		}else{
					$sql=" where ";
						
					if(isset($params['in'])){
						$sql .="{$params['in']['key']} in ({$params['in']['val']})";                        
					}else{
						
			foreach ($params as $key=>$val){
				if($key=='name'){
					if($if_like){
						$sql.="nns_{$key} like '%{$val}%' {$log} ";
					}else{
						$sql.="nns_{$key}='{$val}' {$log} ";
					}
				}else{
					$sql.="nns_{$key}='{$val}' {$log} ";
				}
			}
					}
//			if($if_like===false){
//				foreach($params as $key=>$val){
//					$sql.="nns_{$key}='{$val}' {$log} ";
//				}
//			}else{
//				foreach($params as $key=>$val){
//					$sql.="nns_{$key} like '%{$val}%' {$log} ";
//				}
//			}
			$sql=trim($sql,"{$log} ");
					   
		}
		if(empty($since)&&$since!=="0"&&$since!==0){
			$limit=" ";
		}else{
			if(empty($num)){
				$limit=" limit {$since} ";
			}else{
				$limit=" limit {$since},{$num} ";
			}
		}
		if(!empty($order)){
			$order=self::$order[$order];
		}
				return $sql.$order.$limit;
	}
	/**
	 * 删除缓存key
	 * @param $dc
	 */
	static private function del_cache($dc){
		if(!$dc->is_cache_enabled()){
			return false;
		}
		$dc->cache()->delete("label");
	}


	static public function get_label_info_by_ids($dc,$ids){
			
		$ids_str=implode('","',$ids);
		$ids_str='"'.$ids_str.'"';
		$sql='select * from nns_video_label where '.
			'nns_id in ( '.$ids_str.')';
		$result= nl_query_by_db($sql, $dc->db());
		$result=np_array_rekey($result,'nns_id');
		return $result;
	}
	static public function get_label_info_by_names($dc,$names){
		$ids_str=implode('","',$names);
		$ids_str='"'.$ids_str.'"';
		$sql='select * from nns_video_label where nns_name in ( '.$ids_str.')';
		
		$result= nl_query_by_db($sql, $dc->db());
		$result=np_array_rekey($result,'nns_id');
		return $result;
	}
	static public function get_label_info_by_id($dc,$id){
		$sql='select * from nns_video_label where nns_id = \''.$id.'\'';
		$result= nl_query_by_db($sql, $dc->db());

		return $result;
	}
/**
	 * 根据标签id删除标签，并同时删除该表面绑定的影片信息
	 * @param $dc
	 * @param array $label_id
	 * @return bool
	 */
	static public function del_label($dc,$label_ids=array()){
		//获取标签类型
		$labels=implode("','", $label_ids);
		$labels="'".$labels."'";
		$sql="delete from nns_video_label where nns_id in({$labels})";
		nl_execute_by_db($sql, $dc->db());
		$sql =" delete from nns_assest_lable_bind where nns_label_id in({$labels})";
		nl_execute_by_db($sql, $dc->db());
		foreach ($label_ids as $value) {
			$label_type=substr($value, 0,4);
			$sql="delete from nns_video_label_bind_{$label_type} where nns_label_id in({$labels})";
			//删除缓存
			nl_execute_by_db($sql, $dc->db());
		}
		self::del_cache($dc);
		return true;
	}
}
//$dc=nl_get_dc(array("db_policy"=>NL_DB_WRITE,"cache_policy"=>NP_KV_CACHE_TYPE_MEMCACHE));
//$dc->open();
//$r=nl_video_label::add_video_label($dc,"named3e",array("times"=>12,"type"=>"7000","state"=>1,"source"=>"maidn"));
////////$r=nl_video_label::update_video_label_state_by_id($dc, "001", 0);
////////$r=nl_video_label::count_video_label_times_by_id($dc,"001");
////////$r=nl_video_label::count_video_label($dc,array("type"=>"type","name"=>"name"),true,"or");
////////$params=array(
////////				"type"=>"type",
////////			);
//////////$r=video_label::get_video_label_list ($dc,$params,0,2,NL_ORDER_TIME_ASC,NL_DC_DB);
//////$r=nl_video_label::epg_get_video_label_by_type ($dc,"type",0,2,NL_ORDER_TIME_ASC,NL_DC_DB);
//////echo "<pre>";
//var_dump($r);